#include "distribution_manager.h"

using namespace std;

DistributionManager::DistributionManager(int carCount) : _carCount(carCount) {}
void DistributionManager::assignStudent() {
    cout << "正在给学生分配智能小车..." << endl;
    sortCars();
    sortStudents();
    for (size_t i = 0; i < _carCount; i++) {
        auto stu = _sortedStus[i];
        _sortedCars[i].setStudent(stu);
    }
    cout << "分配完成！！" << endl;
}

int DistributionManager::setCars(vector<SmartCar>& cars) {
    _cars.reserve(cars.size());
    _cars = cars;
    return 0;
}

int DistributionManager::setStuents(vector<Student>& stus) {
    _stus.reserve(stus.size());
    _stus = stus;
    return 0;
}

vector<SmartCar>& DistributionManager::getDistributionCars() {
    return _sortedCars;
}

void DistributionManager::sortCars() {
    _sortedCars.clear();
    for (auto car : _cars) {
        _sortedCars.push_back(car);
    }
    // bubble sort
    for (size_t i = _carCount; i > 0; i--) {
        for (size_t j = 0; j < i - 1; j++) {
            long long current_id = getCarIdNumber(_sortedCars[j]);
            long long after_id = getCarIdNumber(_sortedCars[j + 1]);
            if (current_id > after_id) {
                // swap
                auto tmp = _sortedCars[j];
                // FIX: 不知道这里是否有深浅拷贝的bug问题。
                _sortedCars[j] = _sortedCars[j + 1];
                _sortedCars[j + 1] = tmp;
            }
        }
    }
}

void DistributionManager::sortStudents() {
    _sortedStus.clear();
    for (auto stu : _stus) {
        _sortedStus.push_back(stu);
    }
    // bubble sort
    for (size_t i = _carCount; i > 0; i--) {
        for (size_t j = 0; j < i - 1; j++) {
            int current_id = getStuIdNumber(_sortedStus[j]);
            int after_id = getStuIdNumber(_sortedStus[j + 1]);
            if (current_id > after_id) {
                // swap
                auto tmp = _sortedStus[j];
                _sortedStus[j] = _sortedStus[j + 1];
                _sortedStus[j + 1] = tmp;
            }
        }
    }
}

long long DistributionManager::getCarIdNumber(SmartCar car) {
    string num = car.getID().substr(5, 11);
    return stoll(num);
}

int DistributionManager::getStuIdNumber(Student stu) {
    string num = stu.stuId.substr(0, 6);
    return stoi(num);
}
